package com.example.framework.common.pojo;

import cn.hutool.core.util.StrUtil;
import com.example.framework.common.constant.BaseConstants;
import com.example.framework.common.exception.ErrorCode;
import com.example.framework.common.exception.ServiceException;
import com.example.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.experimental.Accessors;
import org.slf4j.MDC;
import org.springframework.util.Assert;

import java.io.Serial;
import java.io.Serializable;
import java.util.Objects;

/**
 * REST API 返回结果
 *
 * @author hubin
 * @since 2018-06-05
 */
@Data
@Accessors(chain = true)
public class R<T> implements Serializable {

    /**
     * serialVersionUID
     */
    @Serial
    private static final long serialVersionUID = 1L;

    /**
     * 错误码
     *
     * @see ErrorCode#getCode()
     */
    private Integer code;
    /**
     * 返回数据
     */
    private T data;
    /**
     * 错误提示，用户可阅读
     *
     * @see ErrorCode#getMsg()
     */
    private String msg;

    /**
     * 时间戳
     */
    private long ts = System.currentTimeMillis();

    /**
     * 日志ID
     */
    private String logId = MDC.get(BaseConstants.TRACE_UNIQUE_ID);

    private R() {
    }

    public static <T> R<T> success() {
        return R.success(null);
    }

    public static <T> R<T> success(T data) {
        R<T> result = new R<>();
        result.code = GlobalErrorCodeConstants.SUCCESS.getCode();
        result.msg = GlobalErrorCodeConstants.SUCCESS.getMsg();
        result.data = data;
        return result;
    }

    /*R.fail()在业务开发不直接使用，只在异常处理时调用*/

    public static <T> R<T> fail(ErrorCode errorCode) {
        return fail(errorCode.getCode(), errorCode.getMsg());
    }

    public static <T> R<T> fail(Integer code, String message) {
        Assert.isTrue(!Objects.equals(GlobalErrorCodeConstants.SUCCESS.getCode(), code), "code 必须是错误的！");
        R<T> result = new R<>();
        result.code = code;
        result.msg = message;
        return result;
    }

    public static <T> R<T> fail(String msg) {
        return fail(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), msg);
    }

    public static <T> R<T> fail(String format, Object... params) {
        String msg = StrUtil.format(format, params);
        return fail(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), msg);
    }

    public static boolean isSuccess(Integer code) {
        return Objects.equals(code, GlobalErrorCodeConstants.SUCCESS.getCode());
    }

    @JsonIgnore // 避免 jackson 序列化
    public boolean isSuccess() {
        return isSuccess(code);
    }

    // ========= 和 Exception 异常体系集成 =========

    /**
     * 判断是否有异常。如果有，则抛出 {@link ServiceException} 异常
     * 如果没有，则返回 {@link #data} 数据
     */
    @JsonIgnore // 避免 jackson 序列化
    public T getCheckedData() {
        checkError();
        return data;
    }

    /**
     * 判断是否有异常。如果有，则抛出 {@link ServiceException} 异常
     */
    public void checkError() throws ServiceException {
        if (isSuccess()) {
            return;
        }
        // 业务异常
        throw ServiceException.of(new ErrorCode(code, msg));
    }

}
